<template>
  <div
    class="login-container"
    style="background-image: url(/img/bg1.jpg); background-size: cover">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="title-container">
        <!-- <h3 class="title">JOY HK Operation System</h3> -->
        <h3 class="title">AICC Operation System</h3>
        <!-- <lang-select class="set-language"/> -->
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" style="font-size: 22px;" />
        </span>
        <el-input
          v-model="loginForm.username"
          :placeholder="$t('ship.login.username')"
          name="username"
          type="text"
          auto-complete="on"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" style="font-size: 18px;" />
        </span>
        <el-input
          :type="pwdType"
          v-model="loginForm.password"
          placeholder="Password"
          name="password"
          auto-complete="on"
          @keyup.enter="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon icon-class="eye" />
        </span>
      </el-form-item>

      <el-form-item prop="code">
        <div class="vPicBox">
          <el-input v-model="loginForm.code" placeholder="Verification Code" style="width: 60%;" />
          <div class="vPic"   @click="refreshCode">
            <div class="code">
               <SIdentify
                :identify-code="identifyCode"
                :fontSizeMin="26"
                :fontSizeMax="35"
                :contentHeight="32"
              ></SIdentify> 
            <!--  <img  @click="refreshCode" :src="identifyCode" alt="" style="height: 32px;" />-->
            </div>
          </div>
        </div>
      </el-form-item>
      <div class="login-footer">
        <el-checkbox v-model="loginForm.remeberMe" class="remeber-me">Remeber Me</el-checkbox>
        <span @click="retPwd">Forget Password</span>
      </div>
     
      <el-form-item> </el-form-item>

      <el-button
        :loading="loading"
        type="primary"
        style="width: 100%; margin-bottom: 20px;background:#202a8c;border:none;"
        @click.prevent="handleLogin"
        >{{ $t("ship.login.logIn") }}
      </el-button>
    </el-form>
    <el-dialog title="Reset Password" v-model="visible" width="500px" :close-on-click-modal="false" draggable>
      <el-form :model="pwdForm" :rules="rules" ref="retrieveForm" label-width="120">
        <el-form-item label="Email" prop="email">
        <el-input v-model="pwdForm.email" placeholder="Email"></el-input>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="Code" prop="verifyCode">
              <el-input v-model="pwdForm.verifyCode" placeholder="Verification Code" style="width: 60%" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="sendCode" color="#202a8c" style="height: 32px;" :disabled="sendBtnDisabled">{{sendBtnText}}</el-button>
          </el-col>
        </el-row>
        <el-form-item label="New password" prop="password">
          <el-input v-model="pwdForm.password" type="password" show-password placeholder="New password"></el-input>
        </el-form-item>
        <el-form-item label="Confirm Password" prop="comfirmPassword">
          <el-input v-model="pwdForm.comfirmPassword" type="password" show-password placeholder="Confirm Password"></el-input>
        </el-form-item>
    </el-form>
    <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleClose"><Cite></Cite>Cancel</el-button>
                    <el-button type="primary" color="#202a8c" @click="submitForm1">
                        Save
                    </el-button>
                </div>
            </template>
      </el-dialog>
  </div>
</template>

<script>
import SIdentify from "@/components/verifyCode/index.vue";
import { isvalidUsername } from "@/utils/validate";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt" 
import useUserStore from '@/store/modules/user'
import service from '@/utils/request'  
import Md5 from 'js-md5'
import { ElMessage } from 'element-plus'
const userStore = useUserStore()
 
export default {
  name: "login",
  components: {
    SIdentify,
  },
  data() {
    const validCode = (rule, value, callback) => {
      if (this.identifyCode != value) {
        // this.refreshCode();
        callback(new Error("Please enter correct verfication code!"));
      } else {
        callback();
      }
    };
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error("Please enter the correct user name"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("The password length must be greater than 6 digits"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
        code: "",
        remeberMe: false,
      },
      identifyCode: "", // 验证码
      identifyCodes: "1234567890", //验证码随机范围
      loginRules: {
        username: [{ required: true, trigger: "blur", validator: validateUsername }],
        password: [{ required: true, trigger: "blur", validator: validatePassword }],
        code: [
          { required: true, message: "Please enter the verification code!", trigger: "blur" },
          { required: true, validator: validCode, trigger: "blur" },
        ],
      },
      rules: {
        email: [
          { required: true, message: 'Please enter Email', trigger: 'blur' },
        ],
        verifyCode: [
          { required: true, message: 'Please enter verification code', trigger: 'blur' },
        ],
        password: [
          { required: true, message: 'Please enter password', trigger: 'blur' },
          { min: 6, message: 'Password must be at least 6 characters', trigger: 'blur' }
        ],
        comfirmPassword: [
          { required: true, message: 'Please enter password', trigger: 'blur' },
          { validator: (rule, value, callback) => {
            if (value !== this.pwdForm.password) {
              callback(new Error('Passwords do not match'));
            } else {
              callback();
            }
          }}
        ]
      },
      loading: false,
      pwdType: "password",
      retrieveForm:null,
      visible: false, // 控制弹窗显示和隐藏的flag
      sendBtnDisabled: false, 
      sendBtnText: 'Send',   
      pwdForm :{
      email: '',
      source:'WEB',
      salt:'57aa863104574df9b2c967cf040381d',
      
    }
    };
  },

created() {
  this.$nextTick(() => {
    this.getCookie();
  })
  
  },
  mounted() {
    //组件挂载完毕刷新验证码
    this.refreshCode();
   
  },
  methods: {
    refreshCode() {
      this.identifyCode = "";
      this.getCode();
      // this.makeCode(this.identifyCodes, 4);
      // 4位验证码可以根据自己需要来定义验证码位数
    },
    // 随机数
    randomNum(min, max) {
      max = max + 1;
      return Math.floor(Math.random() * (max - min) + min);
    },
    // 随机生成验证码字符串
    makeCode(data, len) {
      for (let i = 0; i < len; i++) {
        this.identifyCode += data[this.randomNum(0, data.length - 1)];
      }
    },
    getCode(){
      service.get('/shipping/sysUser/code').then((res) => {
        // ElMessage.success('The code has been sent successfully.')
        this.identifyCode=res.msg
      })
    },
    showPwd() {
      this.pwdType = this.pwdType === "password" ? "" : "password";
    },
    getCookie()  {
      let username = Cookies.get("username");
      let password = Cookies.get("password");
      let remeberMe = Cookies.get("remeberMe"); 
      if(remeberMe){
        this.loginForm.username = username
        this.loginForm.password = decrypt(password)
        this.loginForm.remeberMe = Boolean(remeberMe)
      }
      // loginForm.value = {
      //   username: username === undefined ? loginForm.value.username : username,
      //   password: password === undefined ? loginForm.value.password :  password,
      //   remeberMe: remeberMe === undefined ? false : Boolean(remeberMe)
      // };
    },
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (!valid) {
          this.refreshCode();
          return false;
        } 
 
        if (this.loginForm.remeberMe) { 
          Cookies.set("username", this.loginForm.username, { expires: 30 });
          Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
          Cookies.set("remeberMe", this.loginForm.remeberMe, { expires: 30 });
      } else {
          // 否则移除
          Cookies.remove("username");
          Cookies.remove("password");
          Cookies.remove("remeberMe");
      }

        this.loading = true; 
      console.log(this.loginForm,111)
        userStore.Login(this.loginForm).then(() => {
          this.loading = false;
          location.href = "/";
        }).catch((err) => {
          this.refreshCode();
          this.loading = false;
        }); 
      });
    },
    retPwd(){
      this.visible = true;
    },
   sendCode (){
      let pwdForm = this.pwdForm
      let reg=/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
      if(!reg.test(pwdForm.email)){
        ElMessage.error('Please enter correct Email')
        return false
      }
      if(!pwdForm.email){
        ElMessage.error('Please enter Email')
        return false  
      }
       // 添加倒计时逻辑
       let countdown = 60
      this.sendBtnDisabled = true
      this.sendBtnText = `${countdown}s`
      
      const timer = setInterval(() => {
        countdown--
        this.sendBtnText = `${countdown}s`
        if (countdown <= 0) {
          clearInterval(timer)
          this.sendBtnDisabled = false
          this.sendBtnText = 'Send'
        }
      }, 1000)
      pwdForm.sign = Md5(pwdForm.email +pwdForm.source+ pwdForm.salt)
      service.post('/shipping/sysUser/verifyCode',pwdForm).then(() => {
        ElMessage.success('The verification code has been sent successfully.')
      }).catch(() => {
        ElMessage.error('The sending failed. Please try again later.')
        clearInterval(timer)
        this.sendBtnDisabled = false
        this.sendBtnText = 'Send'
      })
    },
    handleClose(){
      this.visible = false // 关闭弹窗
    },
    submitForm1(){
        this.$refs.retrieveForm.validate((valid) => {
          if (!valid) {
            return false;
          }
          let pwdForm = {
            email: this.pwdForm.email,
            verifyCode: this.pwdForm.verifyCode,
            password: this.pwdForm.password,
          }      
          service.post('/shipping/sysUser/resetPwd',pwdForm).then((res) => {
            if(res.code==0){
              ElMessage.success('Reset successfully.')
              this.visible = false // 关闭弹窗
            }else{
              ElMessage.error('Reset failed. Please try again later.')
            }
          }).catch(() => {
            ElMessage.error('Reset failed. Please try again later.')
          })
        })
    }
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" src="./login.scss"></style>
